package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.*;
import com.example.demo.mapper.StudentExamMapper;
import com.example.demo.service.IExamService;
import com.example.demo.service.IStudentAnswerService;
import com.example.demo.service.IStudentExamService;
import com.example.demo.service.IStudentService;
import com.example.demo.utils.AjaxJson;
import com.example.demo.utils.UserContext;
import com.example.demo.vo.examVo;
import com.example.demo.vo.studentLookExamVo;
import com.example.demo.vo.studentQuestionVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生考试记录表 服务实现类
 * </p>
 *
 * @author
 * @since 2025-11-10
 */
@Service
public class StudentExamServiceImpl extends ServiceImpl<StudentExamMapper, StudentExam> implements IStudentExamService {

    @Autowired
    IStudentService studentService;

    @Autowired
    IStudentAnswerService studentAnswerService;

    @Autowired
    IExamService examService;

    @Override
    public AjaxJson saveStudent(studentQuestionVo studentExam) {
        //获取学生
        User currentUser = UserContext.getCurrentUser();
        Student student = studentService.getByUserId(currentUser.getUserId());
        if (student == null) return AjaxJson.getError("请先绑定学生信息");
        //检查有没有考试关联
        StudentExam studentExamNow = this.getOne(new QueryWrapper<StudentExam>().eq("exam_id", studentExam.getExamId()).eq("student_id", student.getStudentId()));
        if (studentExamNow == null) {
            this.recordEnter(studentExam.getExamId());
        }
        //更新保存时间
        studentExamNow.setSubmitTime(LocalDateTime.now());
        boolean b = this.updateById(studentExamNow);
        if (!b) return AjaxJson.getError("保存失败");

        Map<Integer, String> seq = new HashMap<>();
        for (studentQuestionVo.questionVo questionVo : studentExam.getQuestionVo()) {
            seq.put(questionVo.getQuestionId(), questionVo.getAnswer());
        }

        //更新答题情况
        List<StudentAnswer> studentAnswerList = studentAnswerService.list(new QueryWrapper<StudentAnswer>().eq("se_id", studentExamNow.getSeId()));
        for (StudentAnswer studentAnswer : studentAnswerList) {
            if (seq.containsKey(studentAnswer.getQuestionId()) && seq.get(studentAnswer.getQuestionId()) != null) {
                studentAnswer.setStudentAnswer(seq.get(studentAnswer.getQuestionId()));
                seq.remove(studentAnswer.getQuestionId());
                studentAnswerService.updateById(studentAnswer);
            }
        }
        //创建答题情况
        for (Map.Entry<Integer,String> entry:seq.entrySet()){
            Integer questionId = entry.getKey();
            String answer = entry.getValue();
            System.out.println(questionId+"  "+ answer);
            if(answer==null|| answer.isEmpty()){
                continue;
            }
            StudentAnswer studentAnswer = new StudentAnswer();
            studentAnswer.setSeId(studentExamNow.getSeId());
            studentAnswer.setQuestionId(questionId);
            studentAnswer.setStudentAnswer(answer);
            studentAnswerService.save(studentAnswer);
        }

        return AjaxJson.getSuccess("保存成功");
    }

    @Override
    public AjaxJson recordEnter(Integer examId) {
        //获取学生
        User currentUser = UserContext.getCurrentUser();
        Student student = studentService.getByUserId(currentUser.getUserId());
        if (student == null) return AjaxJson.getError("请先绑定学生信息");
        StudentExam studentId = this.getOne(new QueryWrapper<StudentExam>().eq("student_id", student.getStudentId()).eq("exam_id", examId));
        if (studentId != null) return AjaxJson.getError("请勿重复进入考试");
        StudentExam studentExam = new StudentExam();
        studentExam.setStudentId(student.getStudentId());
        studentExam.setExamId(examId);
        studentExam.setStartTime(LocalDateTime.now());
        return save(studentExam) ? AjaxJson.getSuccess("记录成功") : AjaxJson.getError("记录失败");
    }

    @Override
    public AjaxJson queryStudent(Integer examId) {
        //获取学生
        User currentUser = UserContext.getCurrentUser();
        Student student = studentService.getByUserId(currentUser.getUserId());
        if (student == null) return AjaxJson.getError("请先绑定学生信息");
        //检查有没有考试关联
        StudentExam studentExamNow = this.getOne(new QueryWrapper<StudentExam>().eq("exam_id", examId));
        if (studentExamNow == null) {
            this.recordEnter(examId);
        }
        //更新保存时间
        studentExamNow.setSubmitTime(LocalDateTime.now());
        boolean b = this.updateById(studentExamNow);
        if (!b) return AjaxJson.getError("保存失败");
        //获取答题情况
        List<studentQuestionVo.questionVo> studentAnswerList = studentAnswerService.list(new QueryWrapper<StudentAnswer>().eq("se_id", studentExamNow.getSeId())).stream().map(studentAnswer -> {
            studentQuestionVo.questionVo question = new studentQuestionVo.questionVo();
            question.setQuestionId(studentAnswer.getQuestionId());
            question.setAnswer(studentAnswer.getStudentAnswer());
            return question;
        }).toList();
        studentQuestionVo studentQuestionVo = new studentQuestionVo();
        studentQuestionVo.setExamId(studentExamNow.getExamId());
        studentQuestionVo.setQuestionVo(studentAnswerList);

        return AjaxJson.getSuccessData(studentQuestionVo);
    }

    @Override
    public AjaxJson submit(studentQuestionVo studentExam) {
        //获取学生
        User currentUser = UserContext.getCurrentUser();
        Student student = studentService.getByUserId(currentUser.getUserId());
        if (student == null) return AjaxJson.getError("请先绑定学生信息");
        //检查有没有考试关联
        StudentExam studentExamNow = this.getOne(new QueryWrapper<StudentExam>().eq("exam_id", studentExam.getExamId()));
        if (studentExamNow == null) return AjaxJson.getError("请先关联考试");
        //更新保存时间
        studentExamNow.setSubmitTime(LocalDateTime.now());
        boolean b = this.updateById(studentExamNow);
        if (!b) return AjaxJson.getError("保存失败");

        Map<Integer, String> seq = new HashMap<>();
        for (studentQuestionVo.questionVo questionVo : studentExam.getQuestionVo()) {
            seq.put(questionVo.getQuestionId(), questionVo.getAnswer());
        }

        //更新答题情况
        List<StudentAnswer> studentAnswerList = studentAnswerService.list(new QueryWrapper<StudentAnswer>().eq("se_id", studentExamNow.getSeId()));
        for (StudentAnswer studentAnswer : studentAnswerList) {
            if (seq.containsKey(studentAnswer.getQuestionId()) && seq.get(studentAnswer.getQuestionId()) != null) {
                studentAnswer.setStudentAnswer(seq.get(studentAnswer.getQuestionId()));
                seq.remove(studentAnswer.getQuestionId());
                studentAnswerService.updateById(studentAnswer);
            }
        }
        //创建答题情况
        for (Map.Entry<Integer,String> entry:seq.entrySet()){
            Integer questionId = entry.getKey();
            String answer = entry.getValue();
            System.out.println(questionId+"  "+ answer);
            if(answer==null|| answer.isEmpty()){
                continue;
            }
            StudentAnswer studentAnswer = new StudentAnswer();
            studentAnswer.setSeId(studentExamNow.getSeId());
            studentAnswer.setQuestionId(questionId);
            studentAnswer.setStudentAnswer(answer);
            studentAnswerService.save(studentAnswer);
        }
        //设置考试状态
        StudentExam byId = this.getById(studentExamNow.getSeId());
        byId.setStatus(1);
        boolean update = this.updateById(byId);
        return update ? AjaxJson.getSuccess("提交成功") : AjaxJson.getError("提交失败");
    }

    @Override
    public AjaxJson queryResult(Integer examId) {
        //基本信息获取
//        User user = UserContext.getCurrentUser();
        Exam byId = examService.getById(examId);
        if(byId==null)return AjaxJson.getError("考试不存在");
        examVo examVo = examService.buildExamVo(byId);
        studentLookExamVo studentLookExamVo = new studentLookExamVo();
        //封装数据
        this.copyExVo(examVo,studentLookExamVo);
        //获取考试关联
        Student byUserId = studentService.getByUserId(27);
        StudentExam one = this.getOne(new QueryWrapper<StudentExam>().eq("exam_id", examId).eq("student_id", byUserId.getStudentId()));
        if(one==null)return AjaxJson.getError("请先关联考试");
        //设置考试状态
        if(one.getStatus()==0){
            studentLookExamVo.setStatus(0);
        }else if (one.getStatus()==1){
            studentLookExamVo.setStatus(3);
        }else if (one.getStatus()==2){
            studentLookExamVo.setStatus(4);
        }
        //获取答题情况
        List<StudentAnswer> studentAnswerList = studentAnswerService.list(new QueryWrapper<StudentAnswer>().eq("se_id", one.getSeId()));
        Map<Integer,String>sap=new HashMap<>();
        studentAnswerList.forEach(studentAnswer -> sap.put(studentAnswer.getQuestionId(),studentAnswer.getStudentAnswer()));
        studentLookExamVo.getQuestionList().forEach(questionVo -> {
            questionVo.setYourAnswer(sap.get(questionVo.getQuestionId()));
        });
        return AjaxJson.getSuccessData(studentLookExamVo);
    }

    private void copyExVo(examVo examVo, studentLookExamVo studentLookExamVo) {
        studentLookExamVo.setExamDuration(examVo.getExamDuration());
        studentLookExamVo.setExamId(examVo.getExamId());
        studentLookExamVo.setExamName(examVo.getExamName());
        studentLookExamVo.setCourseId(examVo.getCourseId());
        studentLookExamVo.setCourseName(examVo.getCourseName());
        studentLookExamVo.setDescription(examVo.getDescription());
        studentLookExamVo.setEndTime(examVo.getEndTime());
        studentLookExamVo.setStartTime(examVo.getStartTime());
        studentLookExamVo.setTotalScore(examVo.getTotalScore());
        studentLookExamVo.setQuestionList(examVo.getQuestionList().stream().map(questionVo -> {
            studentLookExamVo.questionVo question = new studentLookExamVo.questionVo();
            question.setQuestionId(questionVo.getQuestionId());
            question.setQuestionContent(questionVo.getQuestionContent());
            question.setCorrectAnswer(questionVo.getCorrectAnswer());
            question.setDifficulty(questionVo.getDifficulty());
            question.setOptionA(questionVo.getOptionA());
            question.setOptionB(questionVo.getOptionB());
            question.setOptionC(questionVo.getOptionC());
            question.setOptionD(questionVo.getOptionD());
            return question;
        }).toList());
    }


}
